package org.ThreadDemo.juctool;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {
    public static void main(String[] args) throws Exception{
        //模拟6辆车
        int threadCount = 6;

        //模拟2个车位
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < threadCount ; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + " 抢到了车位"+System.currentTimeMillis());
                    //Thread.sleep(5000L);
                    //设置随机停车时间
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    //离开车位
                    semaphore.release();
                    System.out.println(Thread.currentThread().getName() + " 释放访问权限"+System.currentTimeMillis());
                }
            }).start();
        }
    }
}